<template>
  <div class="form-container">
  <el-form :model="emailForm" :rules="rules" ref="emailForm" label-width="80px">
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="emailForm.email" placeholder="请输入邮箱" style="width: 220px"></el-input>
    </el-form-item>
    <el-form-item label="验证码" prop="code">
      <el-input v-model="emailForm.code" placeholder="请输入验证码" style="width: 220px"/>
      <el-button :disabled="isSending" @click="sendCode" type="primary">
        {{ isSending ? `${countdown}s后重新发送` : '发送验证码' }}
      </el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary"  @click="bind">绑定</el-button>
      <el-button type="danger" @click="close">关闭</el-button>
    </el-form-item>
  </el-form>
  </div>
</template>

<script>
import apiService from "@/api/service";
import  userInfoApi  from "@/api/userInfo";
import apiUserInfo from "@/api/userInfo";
import cookie from "js-cookie";
export default {
  data() {
    return {
      emailForm: {
        email: '',
        code: ''
      },
      rules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      isSending: false, // 添加这个属性来控制按钮的可点击状态
      countdown: 600
    }
  },
  methods: {

    close() {
      this.$router.go(-1);   //vue-router内置方法跳转
    },
    sendCode() {
      if (this.isSending) return; // 如果正在发送，则直接返回

      apiService.sendMailCode(this.emailForm.email)
        .then((response) => {
          this.$message.success(response.data);
          this.isSending = true;
          let timer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(timer);
              this.isSending = false;
              this.countdown = 600; // 重置计数器
            }
          }, 1000);
        })
        .catch((response) => {
          this.$message.error("请输入邮箱");
        })
    },
    bind(){
      userInfoApi.updateEmail(this.emailForm.email, this.emailForm.code)
      .then((response) => {
        this.$message.success("修改成功，请重新登录");
        setTimeout(() => {
          this.exit();
        }, 2000); // 延迟2000毫秒（即2秒）
      })
    },
    exit() {
      apiUserInfo.logout().then(() => {
        cookie.remove("uid");
        cookie.remove("name");
        cookie.remove("campus-token");
      });
      this.$router.push('/userlogin')
    },
  }
}
</script>

<style>
.form-container {
  display: flex;
  justify-content: center;
}
</style>
